import json
import os

from django.http import HttpResponse, JsonResponse, FileResponse, Http404
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import paramiko
from scp import SCPClient  # 需额外安装scp模块
from task.models import Task
from mysite import settings


def index(request):
    #return HttpResponse("Hello, world. You're at the iras index.")
    tasks = Task.objects.filter(user=request.user)

    if search_keyword := request.GET.get('search'):
        tasks = tasks.filter(task_name__icontains=search_keyword)

    return render(request, 'task/index.html', {
        'tasks': tasks,
        'search_keyword': request.GET.get('search', '')
    })

# 文件下载接口，提供该接口让消费者下载生产者的文件
def download_static_file(request, filename):
    #file_path = os.path.join(settings.MEDIA_URL, filename)
    #print("文件下载路径：")
   # print(file_path)
    #print(os.path)
    #if not os.path.exists(file_path):
    #    raise Http404("文件不存在")
   # return FileResponse(open(file_path, 'rb'), as_attachment=True, filename=filename)
    file_path = settings.MEDIA_ROOT / 'uploads' / filename

    print(f"[调试] 尝试打开文件路径: {file_path}")

    if file_path.exists():
        return FileResponse(open(file_path, 'rb'), as_attachment=True)
    else:
        raise Http404("文件不存在")

#从消费者下载结果文件，使用scp
def download_file_via_scp(host, port, username, password, remote_path, local_path):
    """
    通过SCP下载文件
    :param host: 远程服务器IP
    :param port: SSH端口（默认22）
    :param username: 用户名
    :param password: 密码
    :param remote_path: 远程文件路径（如：/home/user/file.txt）
    :param local_path: 本地保存路径（如：./downloads/file.txt）
    """
    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动接受未知主机密钥（生产环境应谨慎）

    try:
        # 连接服务器
        ssh.connect(host, port=port, username=username, password=password)

        # 创建SCP客户端
        with SCPClient(ssh.get_transport()) as scp:
            scp.get(remote_path, local_path)
            print(f"文件下载成功: {remote_path} -> {local_path}")

    except Exception as e:
        print(f"下载失败: {str(e)}")
    finally:
        ssh.close()

#更新任务信息
@csrf_exempt
def update_task_result(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'fail', 'message': '仅支持POST请求'}, status=405)

    try:
        data = json.loads(request.body)
        task_id = data.get('task_id')
        status = data.get('status')
        result_img_name = data.get('result_img_name')
        result_xlsx_name = data.get('result_xlsx_name')

        if task_id is None or status is None or result_img_name is None or result_xlsx_name is None:
            return JsonResponse({'status': 'fail', 'message': '参数 task_id/status/result 缺失'}, status=400)

        task = Task.objects.get(id=task_id)
        task.status = status
        task.result_img_name = result_img_name
        task.result_xlsx_name = result_xlsx_name
        task.save()

        if status == 2:
            #如果是完成任务，则需要获得消费者的结果文件，一个图片，一个表格
            download_file_via_scp(host="10.10.69.202",
                port=22,
                username="gwswdp02",
                password="gwswdp",
                remote_path="/home/gwswdp02/TCY/ciac_demask/"+task_id+result_img_name, #消费者结果存放地址，按需修改
                local_path="../media/downloads/"+task_id+result_img_name)
            download_file_via_scp(host="10.10.69.202",
                port=22,
                username="gwswdp02",
                password="gwswdp",
                remote_path="/home/gwswdp02/TCY/ciac_demask/"+task_id+result_xlsx_name, #消费者结果存放地址，按需修改
                local_path="../media/downloads/"+task_id+result_xlsx_name)

        return JsonResponse({'status': 'success', 'message': '更新成功'})

    except Task.DoesNotExist:
        return JsonResponse({'status': 'fail', 'message': f'Task ID {task_id} 不存在'}, status=404)
    except Exception as e:
        return JsonResponse({'status': 'fail', 'message': str(e)}, status=500)